﻿using System;
using System.Collections.Generic;

using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using KhoaLuan.Utils;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using DataAccess;
using log4net;
using Core;

namespace KhoaLuan.MainSys.QuanLyPhanQuyen.Resource
{
    /// <summary>
    /// Summary description for ResourceHandler
    /// </summary>
    public class ResourceHandler : BaseHandler
    {

        public object GetListResource(int page, int numberinpage, string keyword)
        {
            try
            {
                tbResource_Proxy pr = new tbResource_Proxy();
                List<DataAccess.tbResource> list = new List<DataAccess.tbResource>();
                string DataResult = "";
                int totalitem = 0;
                if (keyword == "null" || keyword == "")
                {
                    list = pr.SelectAlltbResource_Proxy();
                    totalitem = list.Count;
                }
                else
                {
                    list = (pr.SelectNo_tbResource_Proxy(keyword)).ToList<DataAccess.tbResource>();
                }

                totalitem = list.Count;
                var list2 = list.Skip((page - 1) * numberinpage).Take(numberinpage).Select(x => new { 
                    x.ResourceID,x.ResourceName,x.TypeResourcecID,CreateDat=x.CreatedDate.ToString("U"),x.Active,x.Image,x.Path,x.Description
                });
                DataResult = new JavaScriptSerializer().Serialize(list2);
                var totallpage = totalitem / numberinpage;
                if (totalitem % numberinpage != 0) totallpage++;

                return new JavaScriptSerializer().Serialize(new { Status = "Success", Data = DataResult, TotalPage = totallpage, CurrentPage = page });
            }
            catch (Exception)
            {
                return new JavaScriptSerializer().Serialize(new { Status = "Error", Data = "" });
            }
        }

        public object DeleteResource(int ResourceID)
        {
            try
            {
                tbResource_Proxy pr = new tbResource_Proxy();
                if (pr.Delete_tbResource_Proxy(ResourceID))
                    return new JavaScriptSerializer().Serialize(new { Status = "Success" });
                return new JavaScriptSerializer().Serialize(new { Status = "Error" });
            }
            catch (Exception)
            {
                return new JavaScriptSerializer().Serialize(new { Status = "Error" });
            }
        }
        public object Insert_tbResource(string ResourceName, string Path, string Image, int Active, string Description, int TypeResourcecID, int OrgID)
        {
            try
            {
                ILog log = LogManager.GetLogger(typeof(DataAccess.tbResource).Name);
                tbResource_Proxy pr = new tbResource_Proxy();
                tbResource a = new tbResource();
                a.ResourceID = 0;
                a.ResourceName = ResourceName;
                a.Path = Path;
                a.Image = Image;
                a.CreatedDate = DateTime.Now;
                a.Active = Active;
                a.Description = Description;
                a.TypeResourcecID = TypeResourcecID;
                a.OrgID = OrgID;
                if (pr.Insert_tbResource_Proxy(a))
                    log.Info(UserLogin.GetUserName + "Thêm mới Org  thành công");
                return new JavaScriptSerializer().Serialize(new { Status = "Success" });
            }
            catch (Exception)
            {
                return new JavaScriptSerializer().Serialize(new { Status = "Error" });
            }
        }
        public object UpdatetbResource(int ResourceID, DateTime CreatedDate, string ResourceName, string Path, string Image, int Active, string Description, int TypeResourcecID,int OrgID)
        {
            ILog log = LogManager.GetLogger(typeof(DataAccess.tbResource).Name);
            tbResource_Proxy pr = new tbResource_Proxy();
            tbResource a = new tbResource();
            a.ResourceID = ResourceID;
            a.ResourceName = ResourceName;
            a.Path = Path;
            a.Image = Image;
            a.Active = Active;
            a.CreatedDate =ConvertType.ToDate( CreatedDate);
            a.Description = Description;
            a.TypeResourcecID = TypeResourcecID;
            a.OrgID = OrgID;
            try
            {

                if (pr.Update_tbResource_Proxy(a))
                    return new JavaScriptSerializer().Serialize(new { Status = "Success" });
                return new JavaScriptSerializer().Serialize(new { Status = "Error" });
            }
            catch (Exception)
            {
                return new JavaScriptSerializer().Serialize(new { Status = "Error" });
            }
        }

        public void clickImport(FileUpload FileUpload1, Label lblThongBao)
        {
            string excelContenType = "application/vnd.ms-excel";
            string excel2010ContenType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            if (!FileUpload1.HasFile)
            {
                lblThongBao.Text = "vui long chon file";
            }

            else
            {
                try
                {
                    if (FileUpload1.PostedFile.ContentType != excelContenType && FileUpload1.PostedFile.ContentType != excel2010ContenType)
                    {
                        lblThongBao.Text = "vui long chon file excel";

                    }
                    else
                    {
                        //  string path = string.Concat(HttpServerUtility.Server.MapPath("~/Temp/" + FileUpload1.FileName));
                        string path = "";

                        FileUpload1.SaveAs(path);
                        string excelConString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", path);

                        OleDbConnection connection = new OleDbConnection();
                        connection.ConnectionString = excelConString;
                        OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
                        connection.Open();
                        OleDbDataReader dr = command.ExecuteReader();
                        string sqlconString = @"Data Source=.\sqlexpress;Initial Catalog=HocSinh;Integrated Security=True";
                        SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlconString);
                        bulkInsert.DestinationTableName = "KhachHang";
                        bulkInsert.WriteToServer(dr);
                        //log.Info(Session.GetCurrentUser().UserName + "da import dữ liệu thành công vào bảng khách hàng.");
                    }
                }
                catch (Exception)
                {

                    //log.Error(Session.GetCurrentUser().UserName + "Import dữ liệu cho bảng khách hàng bị lỗi.");
                }
            }
        }

    }

}